package com.gzk.oeno.ihm.common;

import javax.swing.Icon;

import com.gzk.oeno.tech.hibernate.HibernateManager;
import com.gzk.utils.CustomException;
import com.gzk.utils.data.IdObject;
import com.gzk.utils.ihm.UIUtils;
import com.gzk.utils.ihm.panes.AbstractEditForm;

public abstract class HibernateEditForm<K, T extends IdObject<K>> extends AbstractEditForm<T>{

	private static final Icon ADD_ICON = UIUtils.loadSilentIcon("icons/add_16.png");
	private static final Icon EDIT_ICON = UIUtils.loadSilentIcon("icons/edit_16.png");
	private static final Icon DELETE_ICON = UIUtils.loadSilentIcon("icons/delete_16.png");
	
	private final HibernateManager<K, T> manager;
	
	
	protected HibernateEditForm(HibernateManager<K, T> manager){
		super();
		this.manager = manager;
		getDeleteButton().setIcon(DELETE_ICON);
	}
	

	@Override
	protected boolean editObject(T edited, T original) {
		try {
			manager.createOrUpdate(edited);
		} catch (CustomException e) {
			e.showException();
			return false;
		}
		return true;
	}

	@Override
	public boolean deleteObject(T original) {
		try {
			manager.delete(original);
		} catch (CustomException e) {
			e.showException();
			return false;
		}
		return true;
	}

	
	protected void updateButtonStatus(){
		super.updateButtonStatus();
		getEditButton().setIcon(original != null ? EDIT_ICON : ADD_ICON);
	}
	
}
